package com.czk.utils;

import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 网络工具类
 *
 * @Author:ChenZhangKun
 * @Date: 2021/4/29 11:08
 */
public class NetUtil {
    public static int getPort() {
        int initPort = 7397;
        while (true) {
            if (!isPortUsed(initPort)) {
                break;
            }
            initPort++;
        }
        return initPort;
    }

    public static boolean isPortUsed(int port) {
        boolean flag = false;
        try {
            Socket socket = new Socket("localhost", port);
            socket.close();
            // 被用了
            flag = true;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return flag;
    }

    public static String getLocalhost() throws UnknownHostException {
        return InetAddress.getLocalHost().toString();
    }
}
